package com.shundr.auth.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.shundr.auth.channel.R;
import com.shundr.auth.base.BaseActivity;
import com.shundr.auth.common.util.Base64Util;
import com.shundr.auth.common.util.PictureUtil;
import com.shundr.auth.common.util.ProgressDialogHelper;
import com.shundr.auth.frame.db.model.PictureInfo;
import com.shundr.auth.frame.util.JsonUtil;
import com.shundr.auth.frame.util.LLogger;
import com.shundr.auth.frame.util.StringUtil;
import com.shundr.auth.frame.util.ToastHelper;
import com.shundr.auth.user.http.UserRequest;
import com.shundr.auth.user.model.UserInfo;

public class UserInfoActivity extends BaseActivity implements OnClickListener {

	public static final int NONE = 0;
	public static final int PHOTOHRAPH = 1;// 拍照
	public static final int PHOTOZOOM = 2; // 缩放
	public static final int PHOTORESOULT = 3;// 结果
	public static final String IMAGE_UNSPECIFIED = "image/*";

	private ImageView ivHeadPic;
	private TextView tvName;
	private TextView tvPhone;
	private ImageView ivAuthStatus;

	private RelativeLayout mLayoutUserHead;
	private RelativeLayout mLayoutNoName;
	private RelativeLayout mLayoutNoAuth;
	private LinearLayout mLayoutUserInfo;
	private RelativeLayout mLayoutUserPhone;
	private int authStatus;

	private DisplayImageOptions mOptions;

	private List<PictureInfo> mPictures = new ArrayList<PictureInfo>();

	private UserInfo mUserInfo;

	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			try {
				switch (msg.what) {
				case UserRequest.GET_USER_DETAIL_INFO_SUCCESSED:
					mUserInfo = (UserInfo) msg.obj;
					showUserInfo(mUserInfo);
					mLayoutUserInfo.setVisibility(View.VISIBLE);
					break;
				case UserRequest.REQUEST_FAILED:
					ProgressDialogHelper.dismiss();
					String description = (String) msg.obj;
					ToastHelper.toastShort(mContext, description);
					break;
				case UserRequest.COMMIT_USER_HEAD_SUCCESSED:
					ToastHelper.toastShort(mContext, "头像上传成功");
					new UserRequest(mContext, mHandler).getUserInfoByToken();

					break;
				default:
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			ProgressDialogHelper.dismiss();
			super.handleMessage(msg);

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_info);

		mLayoutUserHead = (RelativeLayout) findViewById(R.id.layout_head);
		mLayoutUserPhone = (RelativeLayout) findViewById(R.id.layout_user_phone);
		mLayoutUserInfo = (LinearLayout) findViewById(R.id.activity_user_info);
		ivHeadPic = (ImageView) findViewById(R.id.iv_user_info_portrait);
		tvName = (TextView) findViewById(R.id.tv_user_info_username);
		tvPhone = (TextView) findViewById(R.id.tv_user_info_phone);
		ivAuthStatus = (ImageView) findViewById(R.id.tv_user_info_certification_status);
		mLayoutNoName = (RelativeLayout) findViewById(R.id.ll_add_name);
		mLayoutNoAuth = (RelativeLayout) findViewById(R.id.ll_data_to_renzheng);
		mLayoutNoAuth.setOnClickListener(this);
		mLayoutUserHead.setOnClickListener(this);
		mLayoutUserPhone.setOnClickListener(this);
		ivHeadPic.setOnClickListener(this);
		// mLayoutNoName.setOnClickListener(this);
		// mLayoutUserPhone.setOnClickListener(this);
		initOptions();
		ProgressDialogHelper.show(mContext, "正在加载中...");
		new UserRequest(mContext, mHandler).getUserInfoByToken();

		btnRight.setVisibility(View.VISIBLE);
		btnRight.setText("添加车辆");
		btnRight.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				startActivity(new Intent(mContext, UserTruckListActivity.class));
			}
		});
	}

	@Override
	protected void onResume() {
		new UserRequest(mContext, mHandler).getUserInfoByToken();
		super.onResume();
	}

	/**
	 * 显示
	 * 
	 * @param info
	 */
	private void showUserInfo(UserInfo info) {
		if (info != null) {
			try {
				String name = info.getUserName();
				if (name != null) {
					tvName.setText(name);
				}
				String phone = info.getUserPhone();
				if (phone != null) {
					tvPhone.setText(phone);
				}
				authStatus = info.getIdValidationStatus();
				switch (authStatus) {
				case 0:
					ivAuthStatus.setImageResource(R.drawable.ic_auth_no);
					break;
				case 1:
					ivAuthStatus.setImageResource(R.drawable.ic_auth_ing);
					break;
				case 2:
					ivAuthStatus.setImageResource(R.drawable.ic_auth_ok);
					break;
				case 3:
					ivAuthStatus.setImageResource(R.drawable.ic_auth_fail);
					break;
				default:
					break;
				}
				String headUrl = info.getUserHeadPic();
				ImageLoader.getInstance().displayImage(headUrl, ivHeadPic,
						mOptions);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	protected void onDestroy() {
		mHandler.removeCallbacksAndMessages(null);
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.iv_user_info_portrait:
			try {
				if (!StringUtil.isNull(mUserInfo.getUserHeadPic())) {
					Intent url = new Intent(mContext, PreviewActivity.class);
					url.putExtra("url", mUserInfo.getUserHeadPic());
					startActivity(url);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case R.id.layout_head:
			PictureUtil.doPickPhotoAction(this);
			break;
		// case R.id.layout_user_phone:
		// startActivity(new Intent(mContext, ChangePhoneActivity.class));
		// break;
		// case R.id.ll_data_to_renzheng:
		// if(authStatus==0||authStatus==3){
		// intent = new Intent(mContext, UserAuthActivity.class);
		// startActivityForResult(intent, 333);
		// }else if(authStatus==1){
		// ToastHelper.toastShort(mContext, "您的认证信息正在审核中");
		// }else if(authStatus==2){
		// ToastHelper.toastShort(mContext, "您已通过认证");
		// }
		// break;
		// case R.id.btn_logout:
		// UserUtil.logout(mContext);
		// new CommonRequest(mContext, new Handler()).saveAppOperate(2);
		// finish();
		// break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		Uri data2 = null;
		if (data == null) {
			data2 = PictureUtil.getImageUri();
		} else {
			data2 = data.getData();
		}
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case PictureUtil.PHOTO_PICKED_WITH_DATA:
				intent.setDataAndType(data2, "image/*");
				intent.putExtra("crop", true);
				// 设置裁剪尺寸
				intent.putExtra("aspectX", 1);
				intent.putExtra("aspectY", 1);
				intent.putExtra("outputX", 250);
				intent.putExtra("outputY", 250);
				intent.putExtra("return-data", true);
				intent.putExtra(MediaStore.EXTRA_OUTPUT,
						PictureUtil.getImageCaiUri());
				startActivityForResult(intent, PictureUtil.PHOTO_CROP);
				break;
			case PictureUtil.CAMERA_WITH_DATA:
				data2 = PictureUtil.getCameraImageCaiUri();
				intent.setDataAndType(data2, "image/*");
				intent.putExtra("crop", true);
				intent.putExtra("aspectX", 1);
				intent.putExtra("aspectY", 1);
				intent.putExtra("outputX", 250);
				intent.putExtra("outputY", 250);
				intent.putExtra("return-data", true);
				intent.putExtra(MediaStore.EXTRA_OUTPUT,
						PictureUtil.getImageCaiUri());
				startActivityForResult(intent, PictureUtil.PHOTO_CROP);
				break;
			case PictureUtil.PHOTO_CROP:
				Bundle bundle = data.getExtras();
				Bitmap myBitmap = (Bitmap) bundle.get("data");
				File file = Base64Util.saveBitmapToFile(myBitmap);
				PictureInfo info = new PictureInfo();
				info.setFileBase64Body(Base64Util.encodeImage(myBitmap));
				myBitmap.recycle();
				info.setFilename(PictureUtil.getCharacterAndNumber() + ".png");
				info.setType(PictureInfo.FileType.head);
				// ImageLoader.getInstance().displayImage("file://" +
				// file.getAbsolutePath(), ivHeadPic,mOptions);
				mPictures.add(info);
				String json = JsonUtil.toJson(mPictures);
				LLogger.e(json);
				// ProgressDialogHelper.show(mContext, "上传头像...");
				new UserRequest(mContext, mHandler).commitUserHead(json);
				break;
			case 501:
				new UserRequest(mContext, mHandler).getUserInfoByToken();
				break;
			default:
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void startPhotoZoom(Uri uri) {
		try {
			Intent intent = new Intent("com.android.camera.action.CROP");
			intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
			intent.putExtra("crop", "true");
			// aspectX aspectY 是宽高的比例
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			// outputX outputY 是裁剪图片宽高
			intent.putExtra("outputX", 400);
			intent.putExtra("outputY", 400);
			intent.putExtra("return-data", true);
			startActivityForResult(intent, PHOTORESOULT);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void initOptions() {
		mOptions = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(R.drawable.iv_head)
				// 设置图片Uri为空或是错误的时候显示的图片
				.showImageOnFail(R.drawable.iv_head).cacheInMemory(true)
				// 设置图片加载/解码过程中错误时候显示的图片
				.cacheInMemory(true)
				// 设置下载的图片是否缓存在内存中
				.cacheOnDisc(true)
				// 设置下载的图片是否缓存在SD卡中
				.considerExifParams(true)
				.imageScaleType(ImageScaleType.EXACTLY_STRETCHED)// 设置图片以如何的编码方式显示
				.bitmapConfig(Bitmap.Config.RGB_565)// 设置图片的解码类型//
				// .decodingOptions(Options decodingOptions)//设置图片的解码配置
				.considerExifParams(true)// 设置图片下载前的延迟
				// .delayBeforeLoading(int delayInMillis)//int
				// delayInMillis为你设置的延迟时间
				// 设置图片加入缓存前，对bitmap进行设置
				// .preProcessor(BitmapProcessor preProcessor)
				// .resetViewBeforeLoading(true)//设置图片在下载前是否重置，复位
				.displayer(new RoundedBitmapDisplayer(45))// 是否设置为圆角，弧度为多少
				// .displayer(new FadeInBitmapDisplayer(100))//是否图片加载好后渐入的动画时间
				.build();// 构建完成
	}
}
